﻿using OpenCvSharp;
using Sdcb.PaddleInference;
using Sdcb.PaddleOCR;
using Sdcb.PaddleOCR.Models;
using System.Diagnostics;

namespace PModelOCR
{
    public class PPOCRTestService
    {
        private static readonly Lazy<PPOCRTestService> lazyInstance = new Lazy<PPOCRTestService>(() => new PPOCRTestService());
        private readonly PaddleOcrAll ocr;
        private PPOCRTestService()
        {
            var basePath = Path.Combine(AppContext.BaseDirectory, "OCRModel");
            string cls_infer = Path.Combine(basePath, "ch_ppocr_mobile_v2.0_cls_slim_infer");
            string det_infer = Path.Combine(basePath, "ch_PP-OCRv4_det_infer");
            string rec_infer = Path.Combine(basePath, "ch_PP-OCRv4_rec_infer");
            string keys = Path.Combine(basePath, "ppocr_keys.txt");
            var model = new FullOcrModel(
                    DetectionModel.FromDirectory(det_infer, ModelVersion.V4),
                    ClassificationModel.FromDirectory(cls_infer, ModelVersion.V2),
                    RecognizationModel.FromDirectory(rec_infer, keys, ModelVersion.V4)
            );
            ocr = new PaddleOcrAll(model, PaddleDevice.Onnx());
        }
        // 公共静态属性，提供全局访问点
        public static PPOCRTestService Instance => lazyInstance.Value;
        public  string OcrImgeToText(string imagePath)
        {
                try
                {
                    using (Mat src = Cv2.ImRead(imagePath))
                    {
                       var va= Stopwatch.StartNew();
                        PaddleOcrResult result = ocr.Run(src);
                        va.Stop();
                        
                        return "识别时间:" + va.ElapsedMilliseconds + "ms,内容：" + result.Text;
                    }
                }
                catch (Exception ex)
                {
                    return "";
                }
        }
        
    }
}
